package com.hxgis.oc.cma.util;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * sign标签工具类
 *
 * @author pjq
 * @date 2021/1/15 17:13
 */
@Slf4j
public class CmaSignGenerator {

    private CmaSignGenerator() {
    }

    /**
     * 对检索参数按键值key进行排序，拼接为参数字符串，然后进行MD5加密生成sign
     *
     * @param urlParams 请求参数
     * @return java.lang.String
     * @author pjq
     * @date 2021/1/15 17:18
     */
    public static String createSign(Map<String, Object> urlParams) {

        StringBuilder paramStringBuilder = new StringBuilder();
        Set<String> keySet = urlParams.keySet();
        List<String> keys = keySet.stream().sorted().collect(Collectors.toList());
        for(int i=0;i<keys.size();i++)
        {
            String key = keys.get(i);
            Object value = urlParams.get(key);
            if(i>0)
            {
                paramStringBuilder.append("&");
            }
            paramStringBuilder.append(key.trim()).append("=").append(String.valueOf(value).trim());
        }

        String paramString = paramStringBuilder.toString();

        String sign = "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            byte[] byteArray = md5.digest(paramString.getBytes(StandardCharsets.UTF_8));
            StringBuilder md5StrBuilder = new StringBuilder();

            for (byte b : byteArray) {
                String hexString = Integer.toHexString(255 & b);
                if (hexString.length() == 1) {
                    md5StrBuilder.append("0").append(hexString);
                } else {
                    md5StrBuilder.append(hexString);
                }
            }
            sign = md5StrBuilder.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            log.error("系统不支持当前加密算法：{}", e.getMessage());
        }
        return sign;
    }
}
